package com.zmj.registry;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 *
 * @author：zhangmj
 * @date：2018/9/22 21:45
 */
@Slf4j
@Service
public class ZkServiceRegistryCenterImpl implements IServiceRegistryCenter {

    @Autowired
    private ZkConfig zkConfig;

    /**
     * zk 写入节点了 zkClient,  Curator实现了对zk的操作
     */
    private CuratorFramework curatorFramework;

    @PostConstruct
    public void connectZk(){
        curatorFramework = CuratorFrameworkFactory.builder().connectString(zkConfig.getZkHost()).sessionTimeoutMs(40).
                retryPolicy(new ExponentialBackoffRetry(100,5,50)).build();
        // 客户端已经连接上zk的服务端了
        curatorFramework.start();
    }

    /**
     * 服务注册
     * @param serviceName
     * @param serviceAddress
     */
    @Override
    public void registry(String serviceName, String serviceAddress) {
        // 组建一个地址  /registry/com.zmj.api.IGPService
        String servicePath = zkConfig.getZkRootPath() + "/" + serviceName;
        // 判断这个节点是否存在，不存在再进行创建
        try {
            if (curatorFramework.checkExists().forPath(servicePath) == null){
                curatorFramework.create().creatingParentContainersIfNeeded()
                        .withMode(CreateMode.PERSISTENT).forPath(servicePath,"0".getBytes());
            }
            log.info("serviceName创建成功：" + servicePath);
            // 在 servicePath下创建临时节点，表示调用的地址，临时节点-服务停止后自动删除
            // /registry/com.zmj.api.IGPService/127.0.0.1
            String addressPath = servicePath + "/" + serviceAddress;
            String addNode = curatorFramework.create().withMode(CreateMode.EPHEMERAL)
                    .forPath(addressPath,"0".getBytes());
            log.info("serviceAddress创建成功：{}" , addNode);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
